package com.ruoyi.project.dj.controller;

import java.util.List;

import com.ruoyi.project.dj.domain.DjThemePartyDay;
import com.ruoyi.project.dj.service.IDjThemePartyDayService;
import com.ruoyi.project.system.user.service.IUserService;
import com.ruoyi.project.system.user.domain.User;
import com.ruoyi.project.system.partymember.service.IPartyMemberService;
import com.ruoyi.project.system.partymember.domain.PartyMember;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.text.Convert;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.MimeTypeUtils;
import com.ruoyi.framework.config.RuoYiConfig;
import com.ruoyi.common.utils.StringUtils;

/**
 * 主题党日Controller
 * 
 * @author ruoyi
 * @date 2023-07-15
 */
@Controller
@RequestMapping("/dj/theme/party/day")
public class DjThemePartyDayController extends BaseController
{
    private String prefix = "dj/theme/party/day";

    @Autowired
    private IDjThemePartyDayService djThemePartyDayService;
    
    @Autowired
    private IUserService userService;
    
    @Autowired
    private IPartyMemberService partyMemberService;

    @RequiresPermissions("dj:theme:party:day:view")
    @GetMapping()
    public String day()
    {
        return prefix + "/day";
    }

    /**
     * 查询主题党日列表
     */
    @RequiresPermissions("dj:theme:party:day:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(DjThemePartyDay djThemePartyDay)
    {
        startPage();
        List<DjThemePartyDay> list = djThemePartyDayService.selectDjThemePartyDayList(djThemePartyDay);
        // 为列表中的每一项设置参与者姓名
        for (DjThemePartyDay item : list) {
            setParticipantNames(item);
        }
        return getDataTable(list);
    }

    /**
     * 导出主题党日列表
     */
    @RequiresPermissions("dj:theme:party:day:export")
    @Log(title = "主题党日", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(DjThemePartyDay djThemePartyDay)
    {
        List<DjThemePartyDay> list = djThemePartyDayService.selectDjThemePartyDayList(djThemePartyDay);
        ExcelUtil<DjThemePartyDay> util = new ExcelUtil<DjThemePartyDay>(DjThemePartyDay.class);
        return util.exportExcel(list, "主题党日数据");
    }

    /**
     * 新增主题党日
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存主题党日
     */
    @RequiresPermissions("dj:theme:party:day:add")
    @Log(title = "主题党日", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(DjThemePartyDay djThemePartyDay,
                              @RequestParam(value = "videoFile", required = false) MultipartFile videoFile,
                              @RequestParam(value = "imageFile", required = false) MultipartFile imageFile)
    {
        try {
            // 处理视频文件上传（不限制文件类型）
            if (videoFile != null && !videoFile.isEmpty()) {
                String filePath = RuoYiConfig.getUploadPath();
                String fileName = FileUploadUtils.upload(filePath, videoFile, (String[]) null);
                djThemePartyDay.setVideoPath(fileName);
            }
            
            // 处理图片文件上传（不限制文件类型）
            if (imageFile != null && !imageFile.isEmpty()) {
                String filePath = RuoYiConfig.getUploadPath();
                String fileName = FileUploadUtils.upload(filePath, imageFile, (String[]) null);
                djThemePartyDay.setImagePath(fileName);
            }
            
            return toAjax(djThemePartyDayService.insertDjThemePartyDay(djThemePartyDay));
        } catch (Exception e) {
            logger.error("主题党日新增失败：", e);
            return error("文件上传失败：" + e.getMessage());
        }
    }

    /**
     * 修改主题党日
     */
    @RequiresPermissions("dj:theme:party:day:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        DjThemePartyDay djThemePartyDay = djThemePartyDayService.selectDjThemePartyDayById(id);
        // 设置参与者姓名
        setParticipantNames(djThemePartyDay);
        mmap.put("djThemePartyDay", djThemePartyDay);
        return prefix + "/edit";
    }

    /**
     * 修改保存主题党日
     */
    @RequiresPermissions("dj:theme:party:day:edit")
    @Log(title = "主题党日", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(DjThemePartyDay djThemePartyDay,
                               @RequestParam(value = "videoFile", required = false) MultipartFile videoFile,
                               @RequestParam(value = "imageFile", required = false) MultipartFile imageFile)
    {
        try {
            // 处理视频文件上传（不限制文件类型）
            if (videoFile != null && !videoFile.isEmpty()) {
                String filePath = RuoYiConfig.getUploadPath();
                String fileName = FileUploadUtils.upload(filePath, videoFile, (String[]) null);
                djThemePartyDay.setVideoPath(fileName);
            }
            
            // 处理图片文件上传（不限制文件类型）
            if (imageFile != null && !imageFile.isEmpty()) {
                String filePath = RuoYiConfig.getUploadPath();
                String fileName = FileUploadUtils.upload(filePath, imageFile, (String[]) null);
                djThemePartyDay.setImagePath(fileName);
            }
            
            return toAjax(djThemePartyDayService.updateDjThemePartyDay(djThemePartyDay));
        } catch (Exception e) {
            logger.error("主题党日修改失败：", e);
            return error("文件上传失败：" + e.getMessage());
        }
    }

    /**
     * 删除主题党日
     */
    @RequiresPermissions("dj:theme:party:day:remove")
    @Log(title = "主题党日", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(djThemePartyDayService.deleteDjThemePartyDayByIds(ids));
    }
    
    /**
     * 查看主题党日明细
     */
    @GetMapping("/view/{id}")
    @Log(title = "主题党日", businessType = BusinessType.OTHER)
    public String view(@PathVariable("id") Long id, ModelMap mmap)
    {
        DjThemePartyDay djThemePartyDay = djThemePartyDayService.selectDjThemePartyDayById(id);
        // 设置参与者姓名
        setParticipantNames(djThemePartyDay);
        mmap.put("djThemePartyDay", djThemePartyDay);
        return prefix + "/view";
    }
    
    /**
     * 文件上传接口
     */
    @RequiresPermissions("dj:theme:party:day:add")
    @PostMapping("/upload")
    @ResponseBody
    public AjaxResult uploadFile(@RequestParam("file") MultipartFile file)
    {
        try {
            if (file.isEmpty()) {
                return error("上传文件不能为空");
            }
            
            String filePath = RuoYiConfig.getUploadPath();
            String fileName = FileUploadUtils.upload(filePath, file, (String[]) null);
            
            AjaxResult ajax = AjaxResult.success();
            ajax.put("fileName", fileName);
            ajax.put("url", fileName);
            return ajax;
        } catch (Exception e) {
            logger.error("文件上传失败：", e);
            return error("文件上传失败：" + e.getMessage());
        }
    }
    
    /**
     * 设置参与者姓名
     * 根据参与者ID列表查询党员姓名并设置到participantNames属性
     */
    private void setParticipantNames(DjThemePartyDay djThemePartyDay) {
        if (djThemePartyDay != null && StringUtils.isNotEmpty(djThemePartyDay.getParticipants())) {
            String[] partyMemberIds = djThemePartyDay.getParticipants().split(",");
            StringBuilder nameBuilder = new StringBuilder();
            
            for (String partyMemberIdStr : partyMemberIds) {
                if (StringUtils.isNotEmpty(partyMemberIdStr.trim())) {
                    try {
                        Long partyMemberId = Long.parseLong(partyMemberIdStr.trim());
                        PartyMember partyMember = partyMemberService.selectPartyMemberById(partyMemberId);
                        if (partyMember != null && StringUtils.isNotEmpty(partyMember.getName())) {
                            if (nameBuilder.length() > 0) {
                                nameBuilder.append(",");
                            }
                            nameBuilder.append(partyMember.getName());
                        }
                    } catch (NumberFormatException e) {
                        // 忽略无效的党员ID
                        logger.warn("无效的党员ID：" + partyMemberIdStr);
                    }
                }
            }
            
            djThemePartyDay.setParticipantNames(nameBuilder.toString());
        }
    }
}